from django.conf import settings
from django.db import models
from django.urls import reverse
from tinymce.models import HTMLField
from apps.account.models import Account


class Category(models.Model):
    nid = models.BigAutoField(primary_key=True)
    name = models.CharField(verbose_name="分类名", max_length=20, unique=True)

    class Meta:
        db_table = 'blog_category'
        verbose_name = '分类'
        verbose_name_plural = verbose_name

    def get_absolute_url(self):
        return reverse('blog:article-list-by-category', args=(self.nid,))

    def __str__(self):
        return self.name


class Article(models.Model):
    nid = models.BigAutoField(primary_key=True)
    title = models.CharField(verbose_name="文章标题", max_length=40)
    desc = models.TextField(verbose_name="文章描述", max_length=200, null=True, blank=True)
    keywords = models.CharField(verbose_name="文章关键词", max_length=100, null=True, blank=True)
    thumbnail = models.CharField(verbose_name="封面", max_length=200, null=True, blank=True)
    content = HTMLField(verbose_name="文章内容")
    top = models.BooleanField(verbose_name="置顶", default=False)

    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    update_time = models.DateTimeField(verbose_name="更新时间", auto_now=True)

    view_count = models.BigIntegerField(verbose_name="阅读数", default=0)
    comment_count = models.BigIntegerField(verbose_name="评论数", default=0)
    up_count = models.BigIntegerField(verbose_name="点赞数", default=0)

    category = models.ForeignKey('Category', verbose_name="文章分类", on_delete=models.PROTECT, related_name='articles')
    author = models.ForeignKey(Account, verbose_name="作者", on_delete=models.PROTECT, related_name='articles')

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'blog_article'
        verbose_name = "文章"
        verbose_name_plural = verbose_name

    def get_related_articles(self):
        if not self.keywords:
            return []
        kw = '|'.join(self.keywords.split(','))
        articles = Article.objects.filter(keywords__iregex=f"({kw})").exclude(pk=self.pk).order_by('-update_time')
        return articles[0: settings.RELATED_ARTICLE_COUNT]

    def serializer(self):
        return dict(
            nid=self.nid,
            title=self.title,
            desc=self.desc,
            thumbnail=self.thumbnail,
            top=self.top,
            update_time=self.update_time.strftime('%Y-%m-%d %H:%M'),
            view_count=self.view_count,
            comment_count=self.comment_count,
            up_count=self.up_count,
            category=self.category.name
        )

    def update_view_count(self):
        self.view_count += 1
        self.save()

    def update_comment_count(self):
        self.comment_count += 1
        self.save()

    def update_up_count(self):
        self.up_count += 1
        self.save()

    @property
    def get_owner(self):
        return self.author.username

    @property
    def get_category(self):
        return self.category.name

    @property
    def get_datetime(self):
        return self.update_time.strftime('%Y-%m-%d %H:%M')

    @property
    def get_year(self):
        return self.update_time.strftime('%Y')

    @property
    def get_month(self):
        return self.update_time.strftime('%m')

    @property
    def get_day(self):
        return self.update_time.strftime('%d')

    def get_absolute_url(self):
        return reverse('blog:article-detail', args=(self.nid,))


class ArticleUp(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    user = models.ForeignKey(Account, on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username + ' 点赞 ' + self.article.title


class Diary(models.Model):
    nid = models.BigAutoField(primary_key=True)
    content = HTMLField(verbose_name="内容")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    class Meta:
        db_table = 'diary'
        verbose_name = "日记"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content[0:20]

    def serializer(self):
        return {
            "month_day": self.get_month + self.get_day,
            "content": self.content
        }

    @property
    def get_year(self):
        return self.create_time.strftime('%Y') + '年'

    @property
    def get_month(self):
        return self.create_time.strftime('%m') + '月'

    @property
    def get_day(self):
        return self.create_time.strftime('%d') + '日'


class Comment(models.Model):
    nid = models.BigAutoField(primary_key=True)
    content = HTMLField(verbose_name="评论内容")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    article = models.ForeignKey(Article, verbose_name="文章", on_delete=models.CASCADE, related_name='comments')

    parent = models.ForeignKey('self', verbose_name="父级", on_delete=models.CASCADE, null=True, blank=True)

    class Meta:
        db_table = 'comment'
        verbose_name = "评论"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content[0:20]

    @property
    def get_parent_username(self):
        if self.parent:
            return self.parent.user.username
        return ''

    def serializer(self):
        return dict(
            nid=self.nid,
            content=self.content,
            time=self.create_time.strftime('%Y/%m/%d %H:%M'),
            user={
                "pk": self.user.pk,
                "username": self.user.username,
                "avatar": self.user.avatar,
            },
            article=self.article.nid,
            parent=self.parent.nid if self.parent else None,
            parentuser=self.get_parent_username,
        )

    @property
    def get_children(self):
        return Comment.objects.filter(parent_id=self.nid)


class Message(models.Model):
    nid = models.BigAutoField(primary_key=True)
    content = models.TextField(verbose_name="留言内容")
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    parent = models.ForeignKey('self', verbose_name="父级", on_delete=models.CASCADE, null=True, blank=True)

    class Meta:
        db_table = 'message'
        verbose_name = "留言"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content[0:20]

    def serializer(self):
        return dict(
            nid=self.nid,
            content=self.content,
            time=self.create_time.strftime('%Y/%m/%d %H:%M'),
            user={
                "username": self.user.username,
                "avatar": self.user.avatar,
            },
            parent=self.parent.nid if self.parent else None,
        )


class Friend(models.Model):
    nid = models.BigAutoField(primary_key=True)
    site_name = models.CharField(verbose_name="名称", max_length=50)
    site_link = models.URLField(verbose_name="网址")
    site_icon = models.URLField(verbose_name="图标")
    site_desc = models.CharField(verbose_name="描述", max_length=150)

    class Meta:
        db_table = 'friend'
        verbose_name = "友链"
        verbose_name_plural = verbose_name
        unique_together = (
            ('site_name', 'site_link'),
        )

    def __str__(self):
        return self.site_name
